package com.ifinc.common.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * User: luotao
 * Date: 12-4-19
 * Time: 12:42:00
 */
public class DateUtils {

    public static final String DIGIT14DATE = "yyyy-MM-dd HH:mm:ss";

    public static final String DIGIT8DATE = "yyyy-MM-dd";

    public static final String DATEFORMAT = "dd/MM/yyyy:HH:mm:ss";


    /**
     * 日期加，减运算
     *
     * @param date   日期
     * @param count  加，减的数量
     * @param format 日期转换格式
     * @return
     */
    public static String addDay(Date date, int count, String format) {
        return strFromDate(addDateDay(date, count), format);
    }

    /**
     * 日期加，减运算
     *
     * @param date  日期
     * @param count 加，减的数量
     * @return
     */
    public static Date addDateDay(Date date, int count) {
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, count);
        return calendar.getTime();
    }

    /**
     * 日期格式转换
     *
     * @param date   日期
     * @param format 日期转换格式
     * @return
     */
    public static String strFromDate(Date date, String format) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        return simpleDateFormat.format(date);
    }

    public static Date strFromDate(String date, String format) {
        SimpleDateFormat simpleDateFormat = null;
        if (format != null && !"".equals(format))
            simpleDateFormat = new SimpleDateFormat(format);
        else {
            simpleDateFormat = new SimpleDateFormat();
        }
        try {
            return simpleDateFormat.parse(date);
        } catch (ParseException e) {

            throw new RuntimeException(e.getMessage());
        }
    }

    public static Date dateFromStr(String date) {
        return strFromDate(date, null);
    }

    public static int getMonth(Date d) {
        Calendar c1 = Calendar.getInstance();
        c1.setTime(d);
        return c1.get(Calendar.MONTH) + 1;
    }

    public static int getDayCountInMonth(Date d) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        System.out.println(calendar.getTime());
        calendar.roll(Calendar.DATE, false);
        return calendar.get(Calendar.DATE);
    }

    public static String strNow8() {
        return strFromDate(new Date(), DIGIT8DATE);
    }

    public static String strNow14() {
        return strFromDate(new Date(), DIGIT14DATE);
    }

    public static String strAddDay(String date, int i) {
        Date d = strFromDate(date, DIGIT8DATE);
        d = addDateDay(d, i);
        return strFromDate(d, DIGIT8DATE);
    }
}
